#!/bin/bash

# 获取当前脚本所在目录
SCRIPT_DIR=$(dirname "$(realpath "$0")")

# 从当前目录开始，向上查找直到找到 CMakeLists.txt 文件，确定项目根目录
PROJECT_DIR=$SCRIPT_DIR
while [ ! -f "$PROJECT_DIR/CMakeLists.txt" ]; do
    PROJECT_DIR=$(dirname "$PROJECT_DIR")
done

# 获取项目根目录名
PROJECT_NAME=$(basename "$PROJECT_DIR")
echo "Project root directory name: $PROJECT_NAME"

# 创建并进入构建目录
BUILD_DIR="$PROJECT_DIR/build"
mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"

# 运行 Cmake 配置和编译项目
cmake ..
make -j 16

# 根据项目名称生成 ELF，BIN 和 HEX 文件路径
ELF_FILE="$BUILD_DIR/${PROJECT_NAME}.elf"
BIN_FILE="$BUILD_DIR/${PROJECT_NAME}.bin"
HEX_FILE="$BUILD_DIR/${PROJECT_NAME}.hex"

# 检查 ELF 文件是否生成成功
if [ -f "$ELF_FILE" ]; then
    # 将 ELF 文件转换为 BIN 文件和 HEX 文件
    arm-none-eabi-objcopy -O binary "$ELF_FILE" "$BIN_FILE"
    arm-none-eabi-objcopy -O ihex "$ELF_FILE" "$HEX_FILE"
    echo "Conversion to BIN and HEX completed"
else
    echo "Error: ELF file not found. Compilation might have failed."
    exit 1
fi

# 删除ELF、BIN 和 HEX 文件之外的所有文件和文件夹
find "$BUILD_DIR" -type f ! -name "${PROJECT_NAME}.elf" ! -name "${PROJECT_NAME}.bin" ! -name "${PROJECT_NAME}.hex" -delete
find "$BUILD_DIR" -type d -empty -delete

# 将 HEX 文件路径转换为 Windows 原生格式（关键修正！）
HEX_FILE_WIN=$(cygpath -w "$HEX_FILE")
BIN_FILE_WIN=$(cygpath -w "$BIN_FILE")

# 生成 J-Link 烧录脚本
JLINK_SCRIPT="$BUILD_DIR/flash.jlink"
cat > "$JLINK_SCRIPT" << EOF
device STM32H723ZG
si SWD
speed 4000
connect
erase
loadfile "$BIN_FILE_WIN" 0x08000000  
verifybin "$BIN_FILE_WIN" 0x08000000 
r
q
EOF

# 执行 J-Link 烧录（替换为你的 J-Link 安装路径）
JLINK_PATH="C:/Program Files/SEGGER/JLink_V770e"  
# JLINK_PATH="C:/Program Files/SEGGER/JLink"  # Windows 示例路径

"$JLINK_PATH/JLink.exe" -CommandFile "$JLINK_SCRIPT"